#!/bin/bash
echo "
###############
## Checking running job is finished or not, and mv data, logs ##
###############"
current_time=$1
case_dir=$2
DATABAK=$3

start_year=`echo $current_time | cut -b1-4`
start_month=`echo $current_time | cut -b5-6`
start_day=`echo $current_time | cut -b7-8`
start_hour=`echo $current_time | cut -b9-10`
start_date=${start_year}${start_month}${start_day}${start_hour}

databak_dir=${DATABAK}/${start_date}
mkdir -p ${databak_dir}

cd ${case_dir}/job_logs
if [ -e jobid.txt ]; then
  job_id=$(tail -1 jobid.txt | cut -d" " -f 4)
  echo job.submit.${start_data} id is: $job_id
else
  echo 'file: jobid.txt not found!'
  exit
fi

find_job=0
while [ $find_job -lt 60000 ]
do squeue | grep $job_id
  if [ $? != 0 ]; then
    echo "end_time: "$(date)
    break
  fi
  find_job=$((${find_job} + 1))
  sleep 10
done

mv ${case_dir}/run/atm/MCV/data/grads_${start_date}0000.dat         ${databak_dir}/
mv ${case_dir}/run/atm/MCV/data/post_${start_date}0000.ctl          ${databak_dir}/
mv ${case_dir}/run/atm/MCV/data/gradsmodelvar_${start_date}0000.dat ${databak_dir}/
mv ${case_dir}/run/atm/MCV/data/model_${start_date}0000.ctl         ${databak_dir}/
mv ${case_dir}/run/atm/MCV/data/gradsphytend_model.dat              ${databak_dir}/
mv ${case_dir}/run/atm/MCV/data/phytend_model.ctl                   ${databak_dir}/
mv ${case_dir}/job_logs/PMCV.error.${start_date}.${job_id}          ${databak_dir}/
mv ${case_dir}/job_logs/PMCV.output.${start_date}.${job_id}         ${databak_dir}/
